import { WeilaPlayer } from "./player/weila_player";
import { WeilaRecorder } from "./recorder/weila_recorder";
import { WeilaOpusEncoder} from "./opus/weila_opus";

const defaultSamplerate = 16000;

class WeilaAudio {
    private audioContext: AudioContext | null;


    constructor() {
        this.audioContext = null;
    }

    public async weilaAudio_init(sampleRate: number) {
        if (this.weilaAudio_isSupported()) {
            let audioContext = window.AudioContext;
            if (!audioContext) {
                // @ts-ignore
                audioContext = window.webkitAudioContext;
            }

            if (!this.audioContext || this.audioContext.state == "closed") {
                this.audioContext = new audioContext({sampleRate: sampleRate});
            }

            if (!this.audioContext) {
                console.log('audioContext is null');
                return false;
            }

            if (this.audioContext.state != 'running') {
                console.log('audioContext is not running, resuming');
                this.audioContext.resume();
            }

            WeilaOpusEncoder.getInstance();
            console.log('audioContext is', this.audioContext);
            
        }

        return true
    }

    public weilaAudio_isSupported(): boolean {
        let audioContext = window.AudioContext;
        if (!audioContext) {
            // @ts-ignore
            audioContext = window.webkitAudioContext;
            console.log('using webkitAudioContext');
        }

        if (!audioContext) {
            return false;
        }

        let scope: any = navigator.mediaDevices || {};
        if (!scope.getUserMedia) {
            scope = navigator
            scope.getUserMedia || 
                (scope.getUserMedia = scope.webkitGetUserMedia);
        }

        if (!scope.getUserMedia) {
            return false;
        }

        return true
    }

    public weilaAudio_getPlayer(sampleRate: number, id: number): WeilaPlayer {
        return new WeilaPlayer(this.audioContext, sampleRate, id);
    }

    public weilaAudio_getRecorder(): WeilaRecorder {
        return new WeilaRecorder(this.audioContext);

    }

    public weilaAudio_getEncoder(): WeilaOpusEncoder {
        return WeilaOpusEncoder.getInstance();
    }
}

export {WeilaAudio}